package com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.repository.HddcB7VolcanicdatatableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.repository.HddcB7VolcanicdatatableRepository;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.repository.entity.HddcB7VolcanicdatatableEntity;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.service.HddcB7VolcanicdatatableService;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.viewobjects.HddcB7VolcanicdatatablePageVO;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.viewobjects.HddcB7VolcanicdatatableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicDataTable.viewobjects.HddcB7VolcanicdatatableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-11-26
 */
@Service
public class HddcB7VolcanicdatatableServiceImpl implements HddcB7VolcanicdatatableService {

    private final HddcB7VolcanicdatatableRepository hddcB7VolcanicdatatableRepository;
    private final HddcB7VolcanicdatatableNativeRepository hddcB7VolcanicdatatableNativeRepository;
    private final VolcanoGeologySurveyDataManaExcelVerifyHandler volcanoGeologySurveyDataManaExcelVerifyHandler;

    @Autowired
    public HddcB7VolcanicdatatableServiceImpl(HddcB7VolcanicdatatableRepository hddcB7VolcanicdatatableRepository,
                                              HddcB7VolcanicdatatableNativeRepository hddcB7VolcanicdatatableNativeRepository,
                                              VolcanoGeologySurveyDataManaExcelVerifyHandler volcanoGeologySurveyDataManaExcelVerifyHandler) {
        this.hddcB7VolcanicdatatableRepository = hddcB7VolcanicdatatableRepository;
        this.hddcB7VolcanicdatatableNativeRepository = hddcB7VolcanicdatatableNativeRepository;
        this.volcanoGeologySurveyDataManaExcelVerifyHandler = volcanoGeologySurveyDataManaExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcB7Volcanicdatatables(HddcB7VolcanicdatatableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB7VolcanicdatatablePageVO> hddcB7VolcanicdatatablePage = this.hddcB7VolcanicdatatableNativeRepository.queryHddcB7Volcanicdatatables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB7VolcanicdatatablePage);
    }


    @Override
    public HddcB7VolcanicdatatableEntity getHddcB7Volcanicdatatable(String id) {
        return this.hddcB7VolcanicdatatableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB7VolcanicdatatableEntity saveHddcB7Volcanicdatatable(HddcB7VolcanicdatatableEntity hddcB7Volcanicdatatable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB7Volcanicdatatable.setUuid(uuid);
        hddcB7Volcanicdatatable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB7Volcanicdatatable.setCreateTime(now);
        hddcB7Volcanicdatatable.setUpdateTime(now);
        hddcB7Volcanicdatatable.setIsValid(PlatformConstants.Y);
        hddcB7Volcanicdatatable.setQualityinspectionStatus(PlatformConstants.N);
        hddcB7Volcanicdatatable.setExtends10(PlatformConstants.Y);
        this.hddcB7VolcanicdatatableRepository.save(hddcB7Volcanicdatatable);
        return hddcB7Volcanicdatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB7VolcanicdatatableEntity updateHddcB7Volcanicdatatable(HddcB7VolcanicdatatableEntity hddcB7Volcanicdatatable) {
        HddcB7VolcanicdatatableEntity entity = hddcB7VolcanicdatatableRepository.findById(hddcB7Volcanicdatatable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcB7Volcanicdatatable);
        hddcB7Volcanicdatatable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB7Volcanicdatatable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB7VolcanicdatatableRepository.save(hddcB7Volcanicdatatable);
        return hddcB7Volcanicdatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB7Volcanicdatatables(List<String> ids) {
        List<HddcB7VolcanicdatatableEntity> hddcB7VolcanicdatatableList = this.hddcB7VolcanicdatatableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB7VolcanicdatatableList) && hddcB7VolcanicdatatableList.size() > 0) {
            for(HddcB7VolcanicdatatableEntity hddcB7Volcanicdatatable : hddcB7VolcanicdatatableList) {
                hddcB7Volcanicdatatable.setIsValid(PlatformConstants.N);
                hddcB7Volcanicdatatable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB7Volcanicdatatable.setUpdateTime(new Date());
                this.hddcB7VolcanicdatatableRepository.save(hddcB7Volcanicdatatable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB7VolcanicdatatableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB7VolcanicdatatableEntity> yhDisasterEntities = hddcB7VolcanicdatatableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB7VolcanicdatatableVO> list=new ArrayList<>();
        for (HddcB7VolcanicdatatableEntity entity:yhDisasterEntities) {
            HddcB7VolcanicdatatableVO yhDisasterVO=new HddcB7VolcanicdatatableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "火山地质调查填图数据表", "火山地质调查填图数据表",
                HddcB7VolcanicdatatableVO.class, "火山地质调查填图数据表.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(volcanoGeologySurveyDataManaExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB7VolcanicdatatableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB7VolcanicdatatableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB7VolcanicdatatableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcB7VolcanicdatatableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).append("条记录").toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @return
     */
    public void saveDisasterList(List<HddcB7VolcanicdatatableVO> list) {
        for (int i = 0; i < list.size(); i++) {
            HddcB7VolcanicdatatableEntity yhDisasterEntity = new HddcB7VolcanicdatatableEntity();
            HddcB7VolcanicdatatableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB7Volcanicdatatable(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB7VolcanicdatatableEntity> hddcB7VolcanicdatatableList = this.hddcB7VolcanicdatatableRepository.queryB7VolcanicdatatableByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcB7VolcanicdatatableList) && hddcB7VolcanicdatatableList.size() > 0) {
            for(HddcB7VolcanicdatatableEntity hddcB7VolcanicdatatableEntity : hddcB7VolcanicdatatableList) {
                hddcB7VolcanicdatatableEntity.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB7VolcanicdatatableEntity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcB7VolcanicdatatableEntity.setIsValid("0");
                this.hddcB7VolcanicdatatableRepository.save(hddcB7VolcanicdatatableEntity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskIds
     */
    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcB7VolcanicdatatableEntity> hddcA1InvrgnhasmaterialtableList = this.hddcB7VolcanicdatatableRepository.queryHddcB7VolcanicdatatableByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcB7VolcanicdatatableEntity hddcB7VolcanicdatatableEntity : hddcA1InvrgnhasmaterialtableList) {
                hddcB7VolcanicdatatableEntity.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB7VolcanicdatatableEntity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcB7VolcanicdatatableEntity.setIsValid("0");
                this.hddcB7VolcanicdatatableRepository.save(hddcB7VolcanicdatatableEntity);
            }
        }

    }


}
